package com.mjk;


import cn.hutool.core.exceptions.ExceptionUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.error.BizException;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.base.work.annotation.BeeWorkProxy;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.util.*;
import com.mjk.common.web.getway.transfer.cloud.CloudGetWayProtocol;
import com.mjk.common.web.getway.utils.RequstParaseUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 如果没有定义CommonService 则初始化该类
 * @author mjk
 *
 */
@Controller
@ConditionalOnBean(value = CloudGetWayProtocol.class)
public class SpecialCloudService implements BeeApplicationListener {
	
	public final Map<String,Object> workMapping = new ConcurrentHashMap<String, Object>();
	public Object getWork(String work){
		Object o = workMapping.get(work.toUpperCase());
		if(null!=o){
			return o;
		}else{
			throw new BizException(BeeError.BEE_FAILD.getMsg());
		}
	}
	
	@ResponseBody
	@RequestMapping("/dohisapi")
	public BeeResponse doCommonApi(HttpServletRequest request) {
		Map<String,Object> map = RequstParaseUtils.getMapFromRequest(request);
		String work = MapUtils.getString(map, "work");
		String method = MapUtils.getString(map, "method");
		if(ObjectUtils.isEmpty(work)){
			throw new BizException("work is null");
		}
		try{
			Object o = getWork(work);
			Method m = ReflectionUtils.getMethod(o.getClass(), method);
			Class<?> clazz = ClassUtil.loadClass(m.getParameters()[0].getParameterizedType().getTypeName());
			Object paramter = BeanUtils.mapToBeanIgnoreCase(map, clazz);
			Object result = m.invoke(o, new Object[]{paramter});
			if(ObjectUtils.isEmpty(result)){
				return BeeError.BEE_FAILD.tranceError();
			}
			return (BeeResponse) result;
		}catch(Exception e){
			BizLogger.error(e);
			BeeResponse response = new BeeResponse();
			response.setCode(BeeError.BEE_FAILD.getCode());
			response.setMsg(ExceptionUtil.getMessage(e));
			return response;
		}
	}
	
	public void doApplicationEvent(ContextRefreshedEvent event) {
		Map<String,Object> beas = event.getApplicationContext().getBeansWithAnnotation(BeeWork.class);
		for(Entry<String,Object> entry : beas.entrySet()){
			//此处有可能回出现代理对象，如果是代理对象要转为非代理对象
			BeeWork work = AopTargetUtils.getTarget(entry.getValue()).getClass().getAnnotation(BeeWork.class);
			if(null==work){
				//do nothing
			}else{
				workMapping.put(work.work().toUpperCase(), entry.getValue());
			}
		}
		//获取代理对象
		Map<String,Object> proxys = event.getApplicationContext().getBeansWithAnnotation(BeeWorkProxy.class);
		for(Entry<String,Object> entry : proxys.entrySet()){
			Object target = AopTargetUtils.getTarget(entry.getValue());
			Class<?> superClazz = target.getClass().getSuperclass();
			if(null!=superClazz && !Object.class.equals(superClazz)){
				BeeWork work = superClazz.getAnnotation(BeeWork.class);
				if(null != work)
					workMapping.put(work.work().toUpperCase(), (entry.getValue()));
			}
		}
	}
}
